package com.punch.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Slf4j
public class OssUtil {
    private static String bucketName;
    private static String ossPath;

    private static final OSS ossClient;
    private static Environment environment = SpringUtil.getBean(Environment.class);

    static {
        bucketName = environment.getProperty("ossInfo.punch.bucketName");
        String endpoint = environment.getProperty("ossInfo.punch.endpoint");
        String accessKeyId = environment.getProperty("ossInfo.punch.accessKeyId");
        String secretAccessKey = environment.getProperty("ossInfo.punch.accessKeySecret");
        ossPath = environment.getProperty("ossInfo.punch.ossPath");
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);
    }

    public static String uploadFile(MultipartFile file, String module) {
        String originalName = file.getOriginalFilename();
        String newName = getFileName(originalName.split("\\.")[1]);
        String path = ossPath + module + newName;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ossClient.putObject(bucketName, module + newName, inputStream);
            return path;
        } catch (IOException e) {
            return e.getMessage();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭文件出错");
            }
        }
    }

    /**
     * 通过原始名称获取随机名称的图片名
     */
    private static String getFileName(String ext) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String name = simpleDateFormat.format(date);
        return name + getSixNumStr() + "." + ext;
    }

    /**
     * 获取六位数字随机数
     */
    private static String getSixNumStr() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

}
